<template>
  <div class="main">
    <el-card class="box-card">
      <template #header>
        <div class="card-header">
          <span>岗位管理</span>
          <div class="header-actions">
            <el-button @click="handleRefresh">
              <IconifyIconOffline icon="ep:refresh" />
              刷新
            </el-button>
          </div>
        </div>
      </template>

      <!-- 条件查询区域 -->
      <div class="search-container">
        <el-form :model="searchForm" inline>
          <el-form-item label="小区">
            <el-select
              v-model="searchForm.cellId"
              placeholder="请选择小区"
              clearable
              style="width: 200px"
            >
              <el-option
                v-for="item in cellOptions"
                :key="item.id"
                :label="item.name"
                :value="item.id"
              />
            </el-select>
          </el-form-item>

          <el-form-item label="岗位类型">
            <el-select
              v-model="searchForm.type"
              placeholder="请选择岗位类型"
              clearable
              style="width: 200px"
            >
              <el-option
                v-for="item in positionTypeOptions"
                :key="item.value"
                :label="item.label"
                :value="item.value"
              />
            </el-select>
          </el-form-item>

          <el-form-item>
            <el-button type="primary" @click="handleSearch">
              <IconifyIconOffline icon="ep:search" />
              查询
            </el-button>
            <el-button @click="handleReset">
              <IconifyIconOffline icon="ep:refresh-right" />
              重置
            </el-button>
          </el-form-item>
        </el-form>
      </div>

      <div class="content">
        <!-- 岗位树形表格 -->
        <el-table
          v-loading="loading"
          :data="positionList"
          border
          stripe
          style="width: 100%"
          row-key="id"
          :tree-props="{ children: 'children', hasChildren: 'hasChildren' }"
        >
          <el-table-column prop="posNumber" label="岗位编号" min-width="140" />

          <el-table-column prop="name" label="岗位名称" min-width="150" />

          <el-table-column prop="type" label="岗位类型" min-width="120">
            <template #default="{ row }">
              <el-tag :type="getPositionTypeTag(row.type)">
                {{ getPositionTypeName(row.type) }}
              </el-tag>
            </template>
          </el-table-column>

          <el-table-column prop="cellName" label="所属小区" min-width="150">
            <template #default="{ row }">
              <span>{{ row.cellName || "-" }}</span>
            </template>
          </el-table-column>

          <el-table-column prop="parentName" label="上级岗位" min-width="150">
            <template #default="{ row }">
              <span>{{ row.parentName || "-" }}</span>
            </template>
          </el-table-column>

          <el-table-column prop="ordered" label="排序" width="80" />

          <el-table-column prop="createTime" label="创建时间" min-width="180">
            <template #default="{ row }">
              <span>{{ formatDate(row.createTime) }}</span>
            </template>
          </el-table-column>

          <el-table-column label="操作" width="250" fixed="right">
            <template #default="{ row }">
              <el-button type="success" size="small" @click="handleEdit(row)">
                编辑
              </el-button>
              <el-button type="danger" size="small" @click="handleDelete(row)">
                删除
              </el-button>
              <el-button
                v-if="row.type !== 2"
                type="primary"
                size="small"
                @click="handleAddChild(row)"
              >
                添加下级
              </el-button>
            </template>
          </el-table-column>
        </el-table>
      </div>
    </el-card>

    <!-- 岗位表单对话框 -->
    <el-dialog
      v-model="dialogVisible"
      :title="dialogTitle"
      width="500px"
      :close-on-click-modal="false"
    >
      <el-form
        ref="formRef"
        :model="formData"
        :rules="formRules"
        label-width="100px"
      >
        <el-form-item label="所属小区" prop="cellId">
          <el-select
            v-model="formData.cellId"
            placeholder="请选择小区"
            style="width: 100%"
            :disabled="isEdit"
          >
            <el-option
              v-for="item in cellOptions"
              :key="item.id"
              :label="item.name"
              :value="item.id"
            />
          </el-select>
        </el-form-item>

        <el-form-item label="岗位类型" prop="type">
          <el-select
            v-model="formData.type"
            placeholder="请选择岗位类型"
            style="width: 100%"
            :disabled="isEdit || isAddChild"
          >
            <el-option
              v-for="item in positionTypeOptions"
              :key="item.value"
              :label="item.label"
              :value="item.value"
            />
          </el-select>
        </el-form-item>

        <el-form-item v-if="!isAddChild" label="上级岗位" prop="parentId">
          <el-tree-select
            v-model="formData.parentId"
            :data="parentPositionOptions"
            placeholder="请选择上级岗位"
            style="width: 100%"
            clearable
            :props="{ value: 'id', label: 'name', children: 'children' }"
            :disabled="isEdit"
          />
        </el-form-item>

        <el-form-item label="岗位编号" prop="posNumber">
          <el-input v-model="formData.posNumber" placeholder="请输入岗位编号" />
        </el-form-item>

        <el-form-item label="岗位名称" prop="name">
          <el-input v-model="formData.name" placeholder="请输入岗位名称" />
        </el-form-item>

        <el-form-item label="排序" prop="ordered">
          <el-input-number
            v-model="formData.ordered"
            :min="0"
            style="width: 100%"
          />
        </el-form-item>
      </el-form>

      <template #footer>
        <el-button @click="dialogVisible = false">取消</el-button>
        <el-button
          :loading="submitLoading"
          type="primary"
          @click="handleSubmit"
        >
          确定
        </el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, onMounted, computed } from "vue";
import { ElMessage, ElMessageBox } from "element-plus";
import type { FormInstance, FormRules } from "element-plus";
import {
  getPositionTree,
  getPositionTreeByQuery,
  getPositionList,
  createPosition,
  updatePosition,
  deletePosition,
  type Position,
  type PositionCreateParams,
  type PositionUpdateParams,
  PositionType,
  PositionLevel
} from "@/api/position";
import { findAllCells, type Cell } from "@/api/cell";

defineOptions({
  name: "SystemPosition"
});

// 响应式数据
const loading = ref(false);
const positionList = ref<Position[]>([]);
const dialogVisible = ref(false);
const submitLoading = ref(false);
const isEdit = ref(false);
const isAddChild = ref(false);
const currentEditId = ref<number | null>(null);
const cellOptions = ref<Cell[]>([]);
const parentPositionOptions = ref<Position[]>([]);

// 搜索表单数据
const searchForm = reactive({
  cellId: undefined as number | undefined,
  type: undefined as PositionType | undefined
});

// 表单数据
const formData = reactive<Partial<PositionCreateParams & PositionUpdateParams>>(
  {
    cellId: undefined,
    type: undefined,
    parentId: undefined,
    posNumber: "",
    name: "",
    ordered: 0
  }
);

// 表单验证规则
const formRules: FormRules = {
  cellId: [{ required: true, message: "请选择所属小区", trigger: "change" }],
  type: [{ required: true, message: "请选择岗位类型", trigger: "change" }],
  posNumber: [
    { required: true, message: "请输入岗位编号", trigger: "blur" },
    { min: 2, max: 50, message: "长度在 2 到 50 个字符", trigger: "blur" }
  ],
  name: [
    { required: true, message: "请输入岗位名称", trigger: "blur" },
    { min: 2, max: 50, message: "长度在 2 到 50 个字符", trigger: "blur" }
  ],
  ordered: [{ required: true, message: "请输入排序", trigger: "blur" }]
};

const formRef = ref<FormInstance>();

// 岗位类型选项
const positionTypeOptions = [
  { label: "机构", value: PositionType.ORGANIZATION },
  { label: "部门", value: PositionType.DEPARTMENT },
  { label: "岗位", value: PositionType.POSITION }
];

// 计算属性
const dialogTitle = computed(() => {
  if (isAddChild.value) return "添加下级岗位";
  return isEdit.value ? "编辑岗位" : "新增岗位";
});

// 格式化日期
const formatDate = (dateString?: string) => {
  if (!dateString) return "-";
  const date = new Date(dateString);
  return date.toLocaleString("zh-CN", {
    year: "numeric",
    month: "2-digit",
    day: "2-digit",
    hour: "2-digit",
    minute: "2-digit",
    second: "2-digit"
  });
};

// 获取岗位类型名称
const getPositionTypeName = (type?: PositionType) => {
  if (type === undefined) return "-";
  const option = positionTypeOptions.find(item => item.value === type);
  return option ? option.label : "-";
};

// 获取岗位类型标签样式
const getPositionTypeTag = (type?: PositionType) => {
  switch (type) {
    case PositionType.ORGANIZATION:
      return "danger";
    case PositionType.DEPARTMENT:
      return "warning";
    case PositionType.POSITION:
      return "success";
    default:
      return "info";
  }
};

// 获取小区列表
const fetchCellList = async () => {
  try {
    const response = await findAllCells();
    if (response.code === 0) {
      cellOptions.value = response.data || [];
    }
  } catch (error) {
    ElMessage.error("获取小区列表失败");
  }
};

// 获取岗位树
const fetchPositionTree = async () => {
  try {
    loading.value = true;
    const response = await getPositionTree({});
    if (response.code === 0) {
      positionList.value = response.data || [];
      // 构建上级岗位选项
      parentPositionOptions.value = buildParentPositionOptions(
        response.data || []
      );
    }
  } catch (error) {
    ElMessage.error("获取岗位列表失败");
  } finally {
    loading.value = false;
  }
};

// 根据条件获取岗位树
const fetchPositionTreeByQuery = async () => {
  try {
    loading.value = true;
    const params: any = {};
    if (searchForm.cellId !== undefined) {
      params.cellId = searchForm.cellId;
    }
    if (searchForm.type !== undefined) {
      params.type = searchForm.type;
    }

    const response = await getPositionTreeByQuery(params);
    if (response.code === 0) {
      positionList.value = response.data || [];
      // 构建上级岗位选项
      parentPositionOptions.value = buildParentPositionOptions(
        response.data || []
      );
    }
  } catch (error) {
    ElMessage.error("获取岗位列表失败");
  } finally {
    loading.value = false;
  }
};

// 搜索
const handleSearch = () => {
  fetchPositionTreeByQuery();
};

// 重置搜索条件
const handleReset = () => {
  searchForm.cellId = undefined;
  searchForm.type = undefined;
  fetchPositionTree();
};

// 构建上级岗位选项
const buildParentPositionOptions = (positions: Position[]) => {
  return positions.map(position => ({
    id: position.id,
    name: position.name,
    children: position.children
      ? buildParentPositionOptions(position.children)
      : []
  }));
};

// 刷新
const handleRefresh = () => {
  if (searchForm.cellId !== undefined || searchForm.type !== undefined) {
    fetchPositionTreeByQuery();
  } else {
    fetchPositionTree();
  }
};

// 新增岗位
const handleAdd = () => {
  isEdit.value = false;
  isAddChild.value = false;
  currentEditId.value = null;
  resetForm();
  dialogVisible.value = true;
};

// 添加下级岗位
const handleAddChild = (row: Position) => {
  isEdit.value = false;
  isAddChild.value = true;
  currentEditId.value = null;
  resetForm();
  formData.cellId = row.cellId;
  formData.parentId = row.id;
  // 下级岗位类型为当前类型的下一级
  if (row.type === PositionType.ORGANIZATION) {
    formData.type = PositionType.DEPARTMENT;
  } else if (row.type === PositionType.DEPARTMENT) {
    formData.type = PositionType.POSITION;
  }
  dialogVisible.value = true;
};

// 编辑岗位
const handleEdit = (row: Position) => {
  isEdit.value = true;
  isAddChild.value = false;
  currentEditId.value = row.id;
  Object.assign(formData, row);
  dialogVisible.value = true;
};

// 删除岗位
const handleDelete = async (row: Position) => {
  try {
    await ElMessageBox.confirm(
      `确定要删除岗位 "${row.name}" 吗？删除后不可恢复！`,
      "删除确认",
      {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning"
      }
    );

    await deletePosition(row.id);
    ElMessage.success("删除成功");
    // 根据是否有搜索条件决定调用哪个API
    if (searchForm.cellId !== undefined || searchForm.type !== undefined) {
      fetchPositionTreeByQuery();
    } else {
      fetchPositionTree();
    }
  } catch (error) {
    if (error !== "cancel") {
      ElMessage.error("删除失败");
    }
  }
};

// 重置表单
const resetForm = () => {
  Object.assign(formData, {
    cellId: undefined,
    type: undefined,
    parentId: undefined,
    posNumber: "",
    name: "",
    ordered: 0
  });
  formRef.value?.clearValidate();
};

// 提交表单
const handleSubmit = async () => {
  if (!formRef.value) return;

  try {
    await formRef.value.validate();
    submitLoading.value = true;

    if (isEdit.value) {
      await updatePosition(formData as PositionUpdateParams);
      ElMessage.success("编辑成功");
    } else {
      await createPosition(formData as PositionCreateParams);
      ElMessage.success("新增成功");
    }

    dialogVisible.value = false;
    // 根据是否有搜索条件决定调用哪个API
    if (searchForm.cellId !== undefined || searchForm.type !== undefined) {
      fetchPositionTreeByQuery();
    } else {
      fetchPositionTree();
    }
  } catch (error) {
    ElMessage.error(isEdit.value ? "编辑失败" : "新增失败");
  } finally {
    submitLoading.value = false;
  }
};

// 组件挂载时获取数据
onMounted(async () => {
  await fetchCellList();
  fetchPositionTree();
});
</script>

<style scoped>
.main {
  padding: 20px;
}

.box-card {
  margin-bottom: 20px;
}

.card-header {
  display: flex;
  align-items: center;
  justify-content: space-between;
}

.header-actions {
  display: flex;
  gap: 8px;
}

.content {
  padding: 20px 0;
}

.search-container {
  padding: 16px;
  margin-bottom: 20px;
  background-color: #f5f7fa;
  border-radius: 4px;
}

.pagination-container {
  display: flex;
  justify-content: flex-end;
  margin-top: 20px;
}

:deep(.el-table) {
  .el-table__row {
    .el-table__cell {
      padding: 8px 0;
    }
  }
}
</style>
